﻿//导入表定义
document.write("<script language='javascript' src='/resources/js/views/defineTable.js'></script>");
document.write("<script language='javascript' src='/resources/js/component.js'></script>");

//导入表定义
var iHeight = document.documentElement.clientHeight-200;//判断表格自适应高度
var page = 1;
var pageSize = 300;
// 多个页面共用一个js，做区分
var level;

var city_html =
	'<label for="city_departmentSelect" class="pl20 pr10 spanstyle">请选择地市：</label>'
	+'<input name="city_departmentSelect" id="city_departmentSelect" class="w100 easyui-combobox" data-options="editable:false";>';
var county_html =
	'<label for="countySelect" class="pl20 pr10 spanstyle">请选择区县：</label>'
	+ '<input name="countySelect" id="countySelect" class="w200 easyui-combobox"  data-options="editable:false"; >';

var action_indicator_type_all="/indicator/type/all.do" //--------------领域
var aimSaveAll = '/report/save/aim/all.do';
var actionCity = "/report/prealarm/area.do";
var actionProvince = "/report/prealarm/province.do";
var action_area_allCity = "/area/query/selfCity.do"; //-- 城市
var action_area_county="/area/query/county.do";//获取区县信息
var action_self_view = "/area/query/self.do";
var action_indicator_count_monitor="/indicator/count/monitor.do";


var allYear="/resources/js/views/allYear.do";
function loadYear(){
	$.get(allYear, function (json) {
		$("#comboboxYear").combobox({
			textField:"text",
			valueField:"id",
			width:'100px',
			height:'28px',
			data:json,
			multiple:true,
			editable:false,
			formatter:function(row){
				var opts;
				if(row.select=="true"){
					row.selected=true;
					opts = "<input type='checkbox' name='year' checked='checked' id='"+row.id+"' value='"+row.id+"'>"+row.text+"</input>";
				}else{
					opts = "<input type='checkbox' name='year' id='"+row.id+"' value='"+row.id+"'>"+row.text+"</input>";
				}
				return opts;
			},
			panelHeight:"auto",
			panelWidth:'100px',
			panelAlign:'left',
			onSelect:function(rec) {
				oCheckbox = document.getElementById(rec.id);
				oCheckbox.checked=true;
				CRUD.queryList();
			},
			onUnselect:function(rec){
				oCheckbox = document.getElementById(rec.id);
				oCheckbox.checked=false;
				CRUD.queryList();
			}
			// ,
			// onLoadSuccess:function(){
			// 	CRUD.queryList();
			// }
		});
	},'json');
}


//清除图形and表格数据
function clearData(){
	$('#tt').datagrid({data:[]});
}

function  showPreAlarmData(data, curPage, pageSize, reportShowColumns) {
	if(data==null||data.length<1){
		return;
	}
	var total = data["size"];
	if (total == "") {
		$('#tt').datagrid({data: []});
		return;
	}
	var totalPage = Math.ceil(total / pageSize);
	var start = (curPage - 1) * pageSize;
	var dataLength = 0;
	data = data["results"];
	if (data != null && data.length > 0) {
		dataLength = data.length;
	}

	$('#tt').datagrid( {
		toolbar:CreateToolBar(),
		height:iHeight,
		frozen:true,
		fitColumns: true,
		striped: true,  //显示条纹，隔行换色
		columns: [reportShowColumns],
		singleSelect: true,// 是否单选
		loadMsg: '数据加载中,请稍后......',
		pageNumber: curPage,//显示数据列用
		pageSize: pageSize,
		pageList: [200, 500, 1000],
		rownumbers: true,
		pagination: true,//打开翻页功能
		data: data
	});

	var p = $('#tt').datagrid('getPager');
	$(p).pagination({
		total: total,
		pageList: [200, 500, 1000],
		pageSize: pageSize,
		pageNumber: curPage,
		beforePageText: '第',
		afterPageText: '页    共 ' + totalPage + ' 页',
		displayMsg: '当前显示 ' + (start + 1) + '-' + (start + dataLength) + ' 条记录 共 ' + total + ' 条记录',
		onSelectPage: function (curPage, pageSize) {
			query(curPage, pageSize);
		},
		onChangePageSize: function (ps) {
			pageSize = ps;
		}
	});
	try{window.parent.unmask();}catch(err){}
}
function doGetProvince(curPage, pageSize,reportShowColumns) {
	var indicatorType= $('#indicator_type_select').combobox("getValue");    //领域编号
	var formsid= $('#formid').combobox("getValue");
	var iname = $('#iname').textbox('getValue');

	var years=$('#comboboxYear').combobox('getText');

	// var yearList = [];
	// if(yeares!=null ||yeares!='' || yeares!=undefined){
	// 	yearList=yeares.split(',');
	// }

	$.get(actionProvince, {"iname":iname, "indicatorType": indicatorType, "years": years, "page": curPage, "pageSize": pageSize,"formsid":formsid}, function (json) {
		if (json.code == 200) {
			showPreAlarmData(json.data, curPage, pageSize, reportShowColumns)
		}else{
			clearData();
		}
	}, "json");
}

function doGetCity(curPage, pageSize, reportShowColumns){
	var indicatorType = $('#indicator_type_select').combobox("getValue");    //领域编号
	indicatorType=indicatorType==""?"-1":indicatorType;
	var areaid;
	if(level=='county'){
		areaid= $('#countySelect').combobox("getValue");    //地域域编号
	}else {
		areaid= $('#city_departmentSelect').combobox("getValue");    //地域域编号
	}
	areaid=areaid==""?"-1":areaid;

	$('#page').val(curPage);
	$('#pageSize').val(pageSize);
	var iname = $('#iname').textbox('getValue');
	var formsid= $('#formid').combobox("getValue");
	var years=$('#comboboxYear').combobox('getText');

	$.get(actionCity, {"iname":iname, "indicatorType": indicatorType, "areaid": areaid, "years": years, "page": curPage, "pageSize": pageSize,"formsid":formsid}, function (json) {
		if (json.code == 200) {
			showPreAlarmData(json.data, curPage, pageSize, reportShowColumns);
		}else{
			clearData();
		}
	}, "json");
}

function query(curPage, pageSize)  {
	curPage = parseInt(curPage);
	pageSize = parseInt(pageSize);

	var reportShowColumns = getreportShowColumns();

	// 获取数据
	if(level=='province'){
		doGetProvince(curPage, pageSize,reportShowColumns);
	}else if(level=='city'||level=='county'){
		doGetCity(curPage, pageSize, reportShowColumns);
	}
}

//------------------------------------------------------------------获取领域指标信息 -------------------------------------------------------------
function loadIndicatorTypeAll(){
	var formsid= $('#formid').combobox("getValue");
	$.getJSON(action_indicator_type_all,{'formsid':formsid}, function (json) {
		if(!json.success){
			 $.messager.alert('提示',json.massage);
			 return;
		}
		$('#indicator_type_select').combobox({
			method : 'GET',
			async : false,
			data : json.data,
			editable : true,
			valueField : 'id',
			textField : 'name',
			onLoadSuccess : function() { // 数据加载完毕事件
				var a = $('#indicator_type_select').combobox('getData');
				if (a.length > 0) {
					$("#indicator_type_select").combobox('select', a[0].id);
				}
			},
			onSelect:function () {
				query(page,pageSize);
			}
		})
	},'json');
}

// ------------------------------------------------获取当前用户区域的信息-------------------------------------------------------
function loadAreaAllCity(){
	// /area/query/selfCity.do
	$.getJSON(action_area_allCity,function (json) {
		/*json.data.unshift({
			id : -1 ,
			name : "全部"
		});*/
		$('#city_departmentSelect').combobox({
			method : 'GET',
			async : false,
			data : json.data,
			editable : true,
			valueField : 'id',
			textField : 'name',
			onLoadSuccess : function() { // 数据加载完毕事件
				var a = $('#city_departmentSelect').combobox('getData');
				if (a.length > 0) {
					$("#city_departmentSelect").combobox('setValue', a[0].id);
				}
				loadIndicatorTypeAll();
			},
			onSelect:function () {
				query(page,pageSize);
			}
		})
	}, 'json');
}

function loadAreaAllCityAndCounty() {
	// /area/query/selfCity.do
	$.getJSON(action_area_allCity, function (json) {
		/*json.data.unshift({
			id : -1 ,
			name : "全部"
		});*/
		$('#city_departmentSelect').combobox({
			method: 'GET',
			async: false,
			data: json.data,
			editable: true,
			valueField: 'id',
			textField: 'name',
			onLoadSuccess: function () { // 数据加载完毕事件
				var a = $('#city_departmentSelect').combobox('getData');
				if (a.length > 0) {
					$("#city_departmentSelect").combobox('select', a[0].id);
				}
				loadIndicatorTypeAll();
			},
			onSelect: function (res) {
				loadCounty(action_area_county, res.id);
			}
		})
	}, 'json');
}
//-----------------------------------------------------------------获取用户所拥有的二级下拉列表菜单-------------------------------------------------------------
function loadCountyView(){
	// /area/query/self.do
	$.getJSON(action_self_view, function (json) {
		var code = json.code;
		if(code!=200){
			alert("网络不好啊！");
			return;
		}

		var data = json.data;
		var page_level = data.level;
		if(page_level === null){
			alert("用户权限配置不合理，请联系系统管理员！");
			return;
		}

		//根据不同的用户权限，控制用户页面显示几级菜单
		if(page_level=="province"||page_level=="city"){
			$("#insert_html").html(city_html+county_html);
			loadAreaAllCityAndCounty();
		}else if(page_level=="county"){
			$("#insert_html").html(county_html);
			//加载区县(只有区县权限的用户)下拉列表
			loadCounty(action_area_allCity, data.id);
		}

	}, "json");
}

//-----------------------------------------------------------------加载区县下拉列表-------------------------------------------------------------
function loadCounty(action_url, id){
	$.get(action_url, {"areaid":id},function (json) {
		$('#countySelect').combobox({
			async:false,
			method:'GET',
			data:json.data,
			editable:true,
			valueField:'id',
			textField:'name',
			onLoadSuccess: function () {
				var a = $('#countySelect').combobox('getData');
				if (a.length > 0) {
					$('#countySelect').combobox('select', a[0].id);
				}
				loadIndicatorTypeAll();
			},
			onSelect:function () {
				query(page,pageSize);
			}
		})
	}, "json");
}

$(document).ready(function () {
	level = $("input:hidden[name='level']").val();

	$('#tt').datagrid( {
		width : '100%',
		height : '100%'
	});

	if(level=='province'){
		loadIndicatorTypeAll();
	}else if(level=='city'){
		loadAreaAllCity();
	}else if(level=='county'){
		loadCountyView();
	}
	loadYear();
});

var CRUD = {
	queryList: function () {
		query(page, pageSize);
	},
	//录入数据
	Update: function () {
		var data=$('#tt').datagrid('getData');    //获取表格所有数据
		var years = $('#comboboxYear').combobox('getText');
		var yearList = [];
		if(years!=null ||years!='' || years!=undefined){
			yearList=years.split(',');
		}
		for (var j = 0; j < data.rows.length; j++) {
			for (var p = 0; p < yearList.length; p++) {
				// alert(data.rows[j][yearList[p]]);
				if(data.rows[j]==null || data.rows[j][yearList[p]]==null || data.rows[j][yearList[p]]=='undefined'){
					data.rows[j][yearList[p]] = '';

				}else if(data.rows[j][yearList[p]].indexOf('_')!=-1){
					data.rows[j][yearList[p]] = data.rows[j][yearList[p]].split("_")[2];
					if(data.rows[j][yearList[p]]=='null'){
						data.rows[j][yearList[p]] = '';
					}
				}

			}
		}

		var i=0;
		var time= setInterval(function(){
			if(i==data.rows.length){
				clearInterval(time);
				//页面初始后才开始初始化复制功能
				comm.datagrid.initExcel2Grid({gid:'tt',inputClass:'datagrid-editable-input'});
				return;
			}
			var rowIndex = $('#tt').datagrid('getRowIndex', data.rows[i]);
			$('#tt').datagrid('beginEdit', rowIndex);
			i++;
		},10);
	},

	//保存数据
	Save:function(){

		var rows = $('#tt').datagrid('getRows');
		for ( var i = 0; i < rows.length; i++) {
			$('#tt').datagrid('endEdit', i);
		}

		var yearList = [];
		var yeares = document.getElementsByName("year");
		for (var i = 0; i < yeares.length; i++) {
			if (yeares[i].checked) {
				yearList.push(yeares[i].value);
			}
		}

		var rows = $("#tt").datagrid("getRows");
		if(rows==null||rows.length<1){
			return;
		}
		var values="";
		for(var i=0; i<rows.length; i++){
			if(rows[i].length<1||rows[i].id.length<1||rows[i].iname.length<1){
				continue;
			}
			var failRow=rows[i].iname;
			values+=rows[i].id+",";

			for(var j = 0; j < yearList.length; j++){
				var yearValue = rows[i][yearList[j]+'aim'];
				if(yearValue!=null && yearValue.length>0 && !isNumber(yearValue)) {
					failRow += yearList[j] + ":" + yearValue + ";";
					continue;
				}
				values+=yearList[j]+":"+yearValue+",";
			}
			values+=";";
			if(failRow.length>rows[i].iname.length){
				$.messager.alert('错误', '名称:['+rows[i].iname+'],'+'['+yearValue+']不正确哦','error');
			}
		}
		var params={
			'aims' : values
		}
		if(submitSaveAll(params)){
			$.messager.alert('成功', '提交成功','success');
		}
	},
	//暂存
	Staging: function (){
		//注意用浏览器做缓存存入的数据量是很小的。
		endEdit();
	}
};

//编辑结束触发事件
function endEdit(){
	var rows = $('#tt').datagrid('getRows');
	for ( var i = 0; i < rows.length; i++) {
		$('#tt').datagrid('endEdit', i);
	}
}

//批量提交
function submitSaveAll(params){
	$.ajax({
		type : "post",
		url : aimSaveAll,
		data : params,
		async : false,
		success : function(data){
			data = eval("(" + data + ")");
			if(data.code!=200){
				alert("数值报错,请重新填写!");
				return false;
			}
		}
	});
	return true;
}

//有小数位,最多4位
function isNumber(str){
	if(str==null||str.length<1){
		return false;
	}
	var reg1= "^(-?\\d+)(\\.\\d+)?$";
	var regExp = new RegExp(reg1);
	return regExp.test(str);
}

//创建表头按钮(编辑全部)
function CreateToolBar() {
	var a = [];
	a.push({
		text: '录入数据',
		iconCls: 'icon-edit',
		handler: function () {
			CRUD.Update();
		}
	});
	a.push('-');

	a.push({
		text: '上报数据',
		iconCls: 'icon-add',
		handler: function () {
			CRUD.Save();
		}
	});
	a.push('-');

	// a.push({
	// 	text: '暂存数据',
	// 	iconCls: 'icon-save',
	// 	handler: function () {
	// 		CRUD.Staging();
	// 	}
	// });
	// a.push('-');

	return a;
}

function getreportShowColumns() {

	var reportShowColumns = [
		defineTableReportAllColumns["iname"],
		defineTableReportAllColumns["code"],
		defineTableReportAllColumns["unit"],
		defineTableReportAllColumns["sname"]
	];

	var yeares = document.getElementsByName("year");
	var year = "";
	var yearList = [];
	for (var i = 0; i < yeares.length; i++) {
		if (yeares[i].checked) {
			yearList.push(yeares[i].value);
			year += yeares[i].value+",";
		}
	}
	if(year!=""){
		year = year.substring(0, year.length-1);
	}

	for(var i=0; i< yearList.length; i++){
		var c = {title:yearList[i], field:yearList[i], width:90,align:"center",
			sortable:true,
			editor : 'text',
			formatter: function (value, row, index) {
				// 数据上报的类型_每年的目标值_数值_显示数据展示时效果的规则_每年的备注
				var tempValue;
				if(value.indexOf('_')!=-1){
					tempValue = value.split('_')[2];
				}
				if(tempValue===null||tempValue==""||tempValue=="null"||tempValue=="NULL"){
					return "";
				}else{
					return tempValue;
				}
			},
			styler: function (value, row, index) {
				/*
                     10  红色#ff0000  预期难以达标
                     20  橙色#FF9933  达标困难
                     30  黄色#ffff00  当年未达标经努力预期可达标
                     40  浅绿#039dea  达到当年标准
                     50  深绿#009966  提前达标
                 */
				var showlevel = value.split('_')[3];
				switch (Number(showlevel)) {
					case 0 :
						return 'background-color:#FFFFFF;';
					case 10 :
						return 'background-color:#ff0000;';
					case 20 :
						return 'background-color:#FF9933;';
					case 30 :
						return 'background-color:#ffff00;';
					case 40 :
						return 'background-color:#039dea;';
					case 50 :
						return 'background-color:#009966;';
				}
				return 'background-color:#FFFFFF;';
			}
		};
		reportShowColumns.push(c);
	}
	reportShowColumns.push(defineTableReportAllColumns['aim']);//目标规划值
	reportShowColumns.push(defineTableReportAllColumns['rname']);//目标规则
	reportShowColumns.push(defineTableReportAllColumns['idesc']);//目标描述

	return reportShowColumns;

}
